package com.lemon.rpcframe.dao.behavior;

import java.util.List;

import com.lemon.rpcframe.annotation.ServiceBehavior;
import com.lemon.rpcframe.dao.DBHelper;
import com.lemon.rpcframe.dao.Total;
import com.lemon.rpcframe.dao.contract.ITaskDefineService;
import com.lemon.rpcframe.dao.entity.TaskDefineBean;
import com.lemon.rpcframe.util.CollectionUtil;

@ServiceBehavior
public class TaskDefineServiceImpl implements ITaskDefineService {
    public static final int DEFAULT_PAGESIZE = 30;

    @Override
    public long insert(TaskDefineBean entity) throws Exception {
        if (null == entity) {
            return 0l;
        }
        long id = 0l;
        Object obj = DBHelper.getInstance().getdaoHelper().sql.insert(entity);
        if (null != obj) {
            id = (long) obj;
        }
        return id;
    }

    @SuppressWarnings("unchecked")
    @Override
    public TaskDefineBean loadByJobID(long jobID) throws Exception {
        String where = String.format(" jobId = %d", jobID);
        List<TaskDefineBean> list = DBHelper.getInstance().getdaoHelper().sql.getListByCustom(TaskDefineBean.class, "", where, "");
        if (CollectionUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public int deleteByJobID(long jobID) throws Exception {
        String where = String.format(" jobId = %d", jobID);
        DBHelper.getInstance().getdaoHelper().sql.deleteByCustom(TaskDefineBean.class, where);
        return 1;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<TaskDefineBean> loadByPage(int pageSize, int page, Total<Integer> total) throws Exception {
        total.setTotal(countAll());
        List<TaskDefineBean> list = DBHelper.getInstance().getdaoHelper().sql.getListByPage(TaskDefineBean.class, "", "", page, pageSize, " triggerDate desc");
        return list;
    }

    @Override
    public int countAll() throws Exception {
        int cnt = DBHelper.getInstance().getdaoHelper().sql.getCount(TaskDefineBean.class, "");
        return cnt;
    }

    @Override
    public TaskDefineBean loadByTaskGroup(String taskID, String taskGroup) throws Exception {
        String where = String.format(" taskID = '%s' and taskGroup='%s' ", taskID, taskGroup);
        List<TaskDefineBean> list = DBHelper.getInstance().getdaoHelper().sql.getListByCustom(TaskDefineBean.class, "", where, "");
        if (CollectionUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

}
